import fs from "fs";
import path from "path";

// 源目录和目标目录
const sourceDir = path.join(process.cwd(), "webapp/src/pages");
const targetDir = path.join(process.cwd(), "webapp/pages");

// 确保目标目录存在
if (!fs.existsSync(targetDir)) {
  fs.mkdirSync(targetDir, { recursive: true });
  console.log(`Created directory: ${targetDir}`);
}

// 复制目录及其内容
function copyDir(src, dest) {
  // 确保目标目录存在
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }

  // 读取源目录内容
  const entries = fs.readdirSync(src, { withFileTypes: true });

  for (const entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);

    if (entry.isDirectory()) {
      // 递归复制子目录
      copyDir(srcPath, destPath);
    } else {
      // 复制文件
      fs.copyFileSync(srcPath, destPath);
      console.log(`Copied: ${srcPath} -> ${destPath}`);
    }
  }
}

// 执行复制
try {
  console.log("Starting copy process...");
  copyDir(sourceDir, targetDir);
  console.log("Copy process completed successfully!");
} catch (error) {
  console.error("Error during copy process:", error);
  process.exit(1);
} finally {
  // 删除原目录
  fs.rmSync(path.dirname(sourceDir), { recursive: true, force: true });
  console.log(`Deleted source directory: ${sourceDir}`);
}
